//
//  ZLStatusListViewModel.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/20.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import Foundation
import SDWebImage

//上拉刷新最大尝试此时
private let maxPullupTryTime = 3
//微博列表数据封装ViewModel
//只有逻辑代码  函数的封装 没有继承轻量级
class ZLStatusListViewModel {
    
    lazy var statusList = [ZLStatusViewModel]()
    
    private var pullupErrorTimes = 0
    //加载微博列表  完成回调 网络请求是否成功
    func loadStatus(pullup: Bool, completion: @escaping (_ isSucess: Bool, _ hansMorePullup: Bool)->()) {
        
        //判断是否时尚啦刷新 检查 上拉错误
        if (pullup && pullupErrorTimes > maxPullupTryTime)
        {
            completion(true, false)
            
            return
        }
        
        //下拉since-id  数组中第一条微博的id
        let since_id = pullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = pullup ? (statusList.last?.status.id ?? 0) : 0
        
        //数据访问层加载数据
        ZLStatusListDAL.loadStatus(since_id: since_id, max_id: max_id) { (liss, isSuccess) in
            
            //判断网卡请求是否成功
            if !isSuccess{
                completion(false, false)
                return
            }
            
            var array = [ZLStatusViewModel]()
            
            for dict in liss {
                
                guard let model = ZLStstuses.yy_model(with: dict) else{
                    
                    continue
                }
                
                array.append(ZLStatusViewModel(model: model))
                
            }
            //字典转模型
            
            if (pullup)
            {
                self.statusList += array
            }
            else
            {
                //下拉刷新将数据拼接在数组的前面
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0 {
                
                self.pullupErrorTimes += 1
                
                completion(isSuccess,false)
                
            }
            else{
                
                //block当做参数传递
                self.cacheSingleImage(list: array, completion: completion)
                
            }
            
        }
        
    }
    //缓存本次微博中的单张图片
    //缓存完单张图片完并且修改配图视图的大小之后再回调
    fileprivate func cacheSingleImage(list: [ZLStatusViewModel], completion: @escaping (_ isSucess: Bool, _ hansMorePullup: Bool)->()){
        
        //调度组
        let group = DispatchGroup()
        //记录数据长度
        var length = 0
        //遍历数组  查找微博数据有单张图片的进行缓存
        for vm in list{
            
            if vm.picUrls?.count != 1{
                
                continue
            }
            
            guard let pic = vm.picUrls?[0].thumbnail_pic,let url = URL(string: pic) else{
                
                
                return
            }
            //print("要缓存的URL\(pic)");
            //图像下载完成会自动保存在沙河中  如果沙河中已经存在的图片就不再下载
            //注意点：如果缓存的图像累计很大，要找后台要图片大小
            
            //入组
            group.enter()
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    
                    vm.updateSingleImageSize(image: image)
                }
                
                
                print("缓存的图片是\(image)长度\(length)")
                
                //出租 -- 放在回调的最后一句
                group.leave()
                
            })
            
        }
        
        //监听调度组情况
        group.notify(queue: DispatchQueue.main) {
            
            print("图像缓存完成\(length/1000)k")
            
            //执行闭包回调
            completion(true,true)
        }
        
    }
    
}
